﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Net;
using System.IO;
using System.Drawing;
using System.Web;
using System.Windows.Forms;

namespace ConcertSpace
{



    public struct Concert
    {
        public string titre;
        public string date;
        public string heure;
        public string lieu;
        public string chemin_img;
        public Bitmap image;
    }
    class ExtracteurHTML
    {

        public string UppercaseWords(string value)
        {
            char[] array = value.ToCharArray();
            // Handle the first letter in the string.
            if (array.Length >= 1)
            {
                if (char.IsLower(array[0]))
                {
                    array[0] = char.ToUpper(array[0]);
                }
            }
            // Scan through the letters, checking for spaces.
            // ... Uppercase the lowercase letters following spaces.
            for (int i = 1; i < array.Length; i++)
            {
                if (array[i - 1] == ' ')
                {
                    if (char.IsLower(array[i]))
                    {
                        array[i] = char.ToUpper(array[i]);
                    }
                }
            }
            return new string(array);
        }


        public Bitmap getImageFromWeb(string url)
        {
            Bitmap bmp = null;

            try
            {
                WebRequest request = WebRequest.Create(url);
                WebResponse response = request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                bmp = new Bitmap(responseStream);
                responseStream.Close();
                response.Close();
            } catch(Exception e) {
                bmp = null;
            }

            return bmp;
        }

        private string RemoveDiacritics(string text)
        {
            return System.Text.Encoding.ASCII.GetString(System.Text.Encoding.GetEncoding(1251).GetBytes(text));
        }


        private int IndexOfEx(string chaine_src, string chaine_recherchee, int start_index)
        {
            return chaine_src.IndexOf(chaine_recherchee, start_index) + chaine_recherchee.Length;
        }

        public string EncoderCGI(string url)
        {
            //string[] caracteres = {"<", ">", "=", "\"", "'", ":", "?", "#", "[", "]", "!", "$", "&", "(", ")", ",", ";", "%" };
            //string[] equivalents = {"%3C", "%3E", "%3D", "%22", "%27", "%3A", "%3F", "%23", "%5B", "%5D", "%21", "%24", "%26", "%28", "%29", "%2C", "%3B", "%25"};
            string[] caracteres = { "&"};
            string[] equivalents = { "%26"};

            for (int i = 0; i < caracteres.Length; i++)
            {
                url = url.Replace(caracteres[i], equivalents[i]);
            }

            return url;
        }
        public string EncoderCGIFull(string url)
        {
            string[] caracteres = {"%", "<", ">", "=", "\"", "'", ":", "?", "#", "[", "]", "!", "$", "&", "(", ")", ",", ";"};
            string[] equivalents = {"%25", "%3C", "%3E", "%3D", "%22", "%27", "%3A", "%3F", "%23", "%5B", "%5D", "%21", "%24", "%26", "%28", "%29", "%2C", "%3B"};
            //string[] caracteres = { "&" };
            //string[] equivalents = { "%26" };

            for (int i = 0; i < caracteres.Length; i++)
            {
                url = url.Replace(caracteres[i], equivalents[i]);
            }

            return url;
        }

        public DateTime getDateTimeFromText(string texte)
        {
            return DateTime.Parse(texte);
        }
        /*
        public DateTime getDateTimeFromText(string texte)
        {
            texte = RemoveDiacritics(texte);

            string[] liste_mois = { "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december", "janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "aout", "septembre", "octobre", "novembre", "decembre" };
            char[] separateur = { ',', ' ' };
            string[] date_split = texte.Split(separateur, StringSplitOptions.RemoveEmptyEntries);
            DateTime t;
            
            if (texte.ToLower().IndexOf("today") >= 0)
            {
                t = DateTime.Today;
            }
            else
            {
                if (texte.ToLower().IndexOf("tomorrow") >= 0)
                {
                    t = DateTime.Today.AddDays(1);
                }
                else
                {
                    int mois = 1, annee, jour;

                    // Chercher le mois en fonction du tableau des mois
                    for (int i = 0; i < liste_mois.Length; i++)
                    {
                        if (texte.ToLower().IndexOf(liste_mois[i]) >= 0)
                        {
                            // Si on a trouvé en anglais
                            if (i <= 11)
                            {
                                mois = i + 1;
                            } else {
                                // Ou en francais
                                mois = (i - 12) + 1;
                            }
                            break;
                        }
                        else
                        {
                            if (liste_mois[i].IndexOf(texte.ToLower().Substring(0, 3)) >= 0)
                            {
                                // Si on a trouvé en anglais
                                if (i <= 11)
                                {
                                    mois = i + 1;
                                }
                                else
                                {
                                    // Ou en francais
                                    mois = (i - 12) + 1;
                                }
                                break;
                            }
                        }
                    }

                    // Si le jour est spécifié
                    if (date_split.Length >= 3)
                    {
                        // Trouver le numéro du jour
                        jour = int.Parse(date_split[2]);

                        
                        // Déduire l'année
                        // On suppose que le concert aura lieu cette année...
                        annee = DateTime.Today.Year;

                        // On part sur cette hypothese
                        t = new DateTime(annee, mois, jour);
                        string jourSemaine = "" + t.DayOfWeek;
                        // ... mais on vérifie quand meme !
                        // Si le jour de la semaine ne correspond pas, c'est qu'il s'agit certainement de l'année prochaine !
                        if (jourSemaine.Substring(0, 3).ToLower() != date_split[0].ToLower())
                        {
                            // C'est l'année prochaine !
                            annee++;
                        }
                    }
                    else
                    {
                        // Trouver le numéro du jour
                        jour = int.Parse(date_split[1]);

                        // On suppose que c'est cette année
                        annee = DateTime.Today.Year;

                        if (mois < DateTime.Today.Month)
                        {
                            // C'est l'an prochain !
                            annee++;
                        }
                    }

                    
                    t = new DateTime(annee, mois, jour);

                }
            }

            return t;
        }
        */

        public bool IsValidMyspaceLink(string urlMyspace)
        {
            bool retour = false;

            if (urlMyspace.EndsWith("/") == false)
            {
                urlMyspace += "/";
            }
            urlMyspace += "classic";

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(urlMyspace);
            WebResponse response = wr.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream());
            string html = sr.ReadToEnd();
            sr.Close();
            response.Close();

            // Si on trouve le lien dans la page, c'est que c'est bien un Myspace valide
            if (html.IndexOf(urlMyspace) != -1)
            {
                retour = true;
            }
            // Si on trouve un Invalid Friend ID, c'est que c'est pas bon !
            if (html.IndexOf("Invalid Friend ID") != -1)
            {
                retour = false;
            }

            return retour;
        }

        public Groupe getInfosFromMyspaceProfilePage(string urlMyspace)
        {
            string chaine_retour = "";
            // MISE A JOUR SUITE AU NOUVEAU LOOK MYSPACE
            // En rajoutant /classic au lien myspace, on accede à la page myspace sans les bandeaux qui empechent la récupération des infos du Myspace
            chaine_retour = urlMyspace + "/shows";  // <= ca c'est plutot cool ! tous les evenements sont sur la meme page !
            urlMyspace += "/classic";   // <= abusé...

            Groupe g_retour = new Groupe();
            g_retour.image_profil = null;

            
            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(urlMyspace);
            //wr.MaximumAutomaticRedirections = 4;
            //wr.MaximumResponseHeadersLength = 10240;
            //wr.UserAgent = "Nokia6680/1.0 (4.04.07) SymbianOS/8.0 Series60/2.6 Profile/MIDP-2.0 Configuration/CLDC-1.1";
            //wr.UserAgent = "W3C_Validator/1.654";
            WebResponse response = wr.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream());
            string html = sr.ReadToEnd();
            sr.Close();
            response.Close();

            /*WebRequest request = WebRequest.Create(urlMyspace);
            WebResponse response = request.GetResponse();
            StreamReader responseStream = new StreamReader(response.GetResponseStream());
            string html = responseStream.ReadToEnd();*/

            int index_event_atr;
            int index_debut, index_fin;

            if (html.IndexOf("<div id=\"profile_bandschedule\">") != -1)
            {
                // Récupérer le chemin d'accès vers le Myspace Events
                index_event_atr = IndexOfEx(html, "<div id=\"profile_bandschedule\">", 0);
                index_debut = IndexOfEx(html, "<a href=\"", index_event_atr);
                index_fin = html.IndexOf("\"", index_debut);
                chaine_retour = html.Substring(index_debut, index_fin - index_debut);
                if (chaine_retour.EndsWith("/") == true)
                {
                    chaine_retour = chaine_retour.Substring(0, chaine_retour.Length - 1);
                }

                // Si on a un chemin d'accecs relatif
                if (chaine_retour.IndexOf("http://") == -1)
                {
                    chaine_retour = "http://www.myspace.com" + chaine_retour;
                }
            }
            else
            {
                /*if (html.IndexOf("<div id=\"profile_bandschedule\">") != -1)
                {
                "http://profile.myspace.com/index.cfm?fuseaction=user.viewprofile&friendid="*/

            }
            g_retour.urlMyspaceEvents = chaine_retour;

            //if (html.IndexOf("rel=\"myspace:photo\" href=\"http://viewmorepics.myspace.com/index.cfm?fuseaction=user.viewAlbums&amp;friendID=") != -1)
            /*if (html.IndexOf("<img class=\"profilePic\"") != -1)
            {
                // Récupérer le chemin d'accès vers le Myspace Events
                //index_event_atr = IndexOfEx(html, "rel=\"myspace:photo\" href=\"http://viewmorepics.myspace.com/index.cfm?fuseaction=user.viewAlbums&amp;friendID=", 0);
                index_event_atr = IndexOfEx(html, "<img class=\"profilePic\"", 0);
                //index_debut = IndexOfEx(html, "<img src=\"", index_event_atr);
                index_debut = IndexOfEx(html, " src=\"", index_event_atr);
                index_fin = html.IndexOf("\"", index_debut);
                chaine_retour = html.Substring(index_debut, index_fin - index_debut);

                g_retour.image_profil = getImageFromWeb(chaine_retour);
            }
            else
            {
                if (html.IndexOf("rel=\"myspace:photo\" href=\"/") != -1)
                {
                    // Récupérer le chemin d'accès vers le Myspace Events
                    index_event_atr = IndexOfEx(html, "rel=\"myspace:photo\" href=\"/", 0);
                    index_debut = IndexOfEx(html, "<img src=\"", index_event_atr);
                    index_fin = html.IndexOf("\"", index_debut);
                    chaine_retour = html.Substring(index_debut, index_fin - index_debut);

                    g_retour.image_profil = getImageFromWeb(chaine_retour);
                }
            }*/

            g_retour.image_profil = getProfilePhoto(urlMyspace);

            return g_retour;
        }

        
        public Bitmap getProfilePhoto(string urlMyspace)
        {
            // MISE A JOUR SUITE AU NOUVEAU LOOK MYSPACE
            // En rajoutant /classic au lien myspace, on accede à la page myspace sans les bandeaux qui empechent la récupération des infos du Myspace
            //urlMyspace += "/classic";   // <= abusé...

            Bitmap b = null;
            string chaine_retour = "";
            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(urlMyspace);
            //wr.MaximumAutomaticRedirections = 4;
            //wr.MaximumResponseHeadersLength = 10240;
            //wr.UserAgent = "Nokia6680/1.0 (4.04.07) SymbianOS/8.0 Series60/2.6 Profile/MIDP-2.0 Configuration/CLDC-1.1";
            //wr.UserAgent = "W3C_Validator/1.654";
            WebResponse response = wr.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream());
            string html = sr.ReadToEnd();
            sr.Close();
            response.Close();
            

            /*WebRequest request = WebRequest.Create(urlMyspace);
            WebResponse response = request.GetResponse();
            StreamReader responseStream = new StreamReader(response.GetResponseStream());
            string html = responseStream.ReadToEnd();*/

            int index_event_atr;
            int index_debut, index_fin;

            //if (html.IndexOf("rel=\"myspace:photo\" href=\"http://viewmorepics.myspace.com/index.cfm?fuseaction=user.viewAlbums&amp;friendID=") != -1)
            if (html.IndexOf("<img class=\"profilePic\"") != -1)
            {
                // Récupérer le chemin d'accès vers le Myspace Events
                //index_event_atr = IndexOfEx(html, "rel=\"myspace:photo\" href=\"http://viewmorepics.myspace.com/index.cfm?fuseaction=user.viewAlbums&amp;friendID=", 0);
                index_event_atr = IndexOfEx(html, "<img class=\"profilePic\"", 0);
                index_debut = IndexOfEx(html, " src=\"", index_event_atr);
                index_fin = html.IndexOf("\"", index_debut);
                chaine_retour = html.Substring(index_debut, index_fin - index_debut);

                b = getImageFromWeb(chaine_retour);
            }
            else
            {
                if (html.IndexOf(" class=\"miniProfile\" ") != -1)
                {
                    index_event_atr = html.IndexOf(" class=\"miniProfile\" ");
                    index_debut = IndexOfEx(html, "<img src=\"", index_event_atr);
                    index_fin = html.IndexOf("\"", index_debut);
                    chaine_retour = html.Substring(index_debut, index_fin - index_debut);
                    
                    b = getImageFromWeb(chaine_retour);
                }
                else
                {
                    if (html.IndexOf("rel=\"myspace:photo\" href=\"/") != -1)
                    {
                        // Récupérer le chemin d'accès vers le Myspace Events
                        index_event_atr = IndexOfEx(html, "rel=\"myspace:photo\" href=\"/", 0);
                        index_debut = IndexOfEx(html, "<img src=\"", index_event_atr);
                        index_fin = html.IndexOf("\"", index_debut);
                        chaine_retour = html.Substring(index_debut, index_fin - index_debut);

                        b = getImageFromWeb(chaine_retour);
                    }
                }
            }

            return b;
        }

        string MajusculePremiereLettre(string texte)
        {
            return texte[0].ToString().ToUpper() + texte.Substring(1).ToLower();
        }

        public string ChercherAdresseSurGoogle(string texte_recherche)
        {
            string retour;
            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://maps.google.fr/maps?hl=fr&q=" + texte_recherche);
            //wr.MaximumAutomaticRedirections = 4;
            //wr.MaximumResponseHeadersLength = 10240;
            //wr.UserAgent = "Nokia6680/1.0 (4.04.07) SymbianOS/8.0 Series60/2.6 Profile/MIDP-2.0 Configuration/CLDC-1.1";
            //wr.UserAgent = "W3C_Validator/1.654";
            WebResponse response = wr.GetResponse();
            Encoding enc = Encoding.GetEncoding(1252);  // Windows default Code Page
            StreamReader sr = new StreamReader(response.GetResponseStream(), enc);
            string html = sr.ReadToEnd();
            sr.Close();
            response.Close();

            // Prendre le premier résultat proposé par gmaps
            html = html.Substring(IndexOfEx(html, "<span dir=\"ltr\" class=\"pp-headline-item pp-headline-address\"><span>", 0));

            // Prendre entre la fin de <span> et le début de </span>
            retour = html.Substring(0, html.IndexOf("</span>"));
            if(retour == "")
            {
                retour = texte_recherche;
            }
            return retour;

        }

        public int getConcerts(string urlMyspaceEvents, ref ArrayList liste_concert)
        {
            int compteur_ajouts = 0;
            string morceau_lieu;

            // MISE A JOUR SUITE AU NOUVEAU LOOK MYSPACE
            // On a un URL du type http://events.myspace.com/Events/1
            // On veut un URL du type http://www.myspace.com/shows
            urlMyspaceEvents = urlMyspaceEvents.Replace("events.", "www.");
            urlMyspaceEvents = urlMyspaceEvents.Replace("Events", "shows");

            if (urlMyspaceEvents.IndexOf("http://") >= 0)
            {
                Concert c;

                HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(urlMyspaceEvents);
                //wr.MaximumAutomaticRedirections = 4;
                //wr.MaximumResponseHeadersLength = 10240;
                //wr.UserAgent = "Nokia6680/1.0 (4.04.07) SymbianOS/8.0 Series60/2.6 Profile/MIDP-2.0 Configuration/CLDC-1.1";
                //wr.UserAgent = "W3C_Validator/1.654";
                WebResponse response = wr.GetResponse();
                //Encoding enc = Encoding.GetEncoding(1252);  // Windows default Code Page
                StreamReader sr = new StreamReader(response.GetResponseStream());
                string html = sr.ReadToEnd();
                sr.Close();
                response.Close();

                /*WebRequest request = WebRequest.Create(urlMyspaceEvents);
                WebResponse response = request.GetResponse();
                StreamReader responseStream = new StreamReader(response.GetResponseStream());
                string html = responseStream.ReadToEnd();*/

                html = HttpUtility.HtmlDecode(html);

                int index_event_atr;
                int index_debut, index_fin;

                

                index_fin = 0;
                // NOUVELLE PROCEDURE SUITE A MAJ MYSPACE
                while (html.IndexOf("<li class=\"moduleItem event") != -1)
                {
                    html = html.Substring(IndexOfEx(html, "<li class=\"moduleItem event", index_fin));

                    c = new Concert();

                    /*
                    // Récupérer le mois
                    index_debut = IndexOfEx(html, "<span class=\"month\">", 0);
                    index_fin = html.IndexOf("</span>", index_debut);
                    c.date = html.Substring(index_debut, index_fin - index_debut).Replace(".", "").Trim();
                    // Récupérer le jour
                    index_debut = IndexOfEx(html, "<span class=\"day\">", index_fin);
                    index_fin = html.IndexOf("</span>", index_debut);
                    c.date += " " + html.Substring(index_debut, index_fin - index_debut).Trim();
                    */

                    index_debut = IndexOfEx(html, "<a href=\"", 0);
                    index_debut = IndexOfEx(html, "\">", index_debut);
                    index_fin = html.IndexOf("</a>", index_debut);
                    c.titre = html.Substring(index_debut, index_fin - index_debut);
                    c.titre = c.titre.Trim();

                    /* Mise à jour de la part de Myspace !  */
                    
                    // Commenté car info redondante avec le titre
                    /*index_debut = IndexOfEx(html, "<span class=\"fn org hide\">", index_fin);
                    index_fin = html.IndexOf("</span>", index_debut);
                    c.lieu = html.Substring(index_debut, index_fin - index_debut);*/

                    index_debut = IndexOfEx(html, "<span class=\"locality\">", index_fin);
                    index_fin = html.IndexOf("</span>", index_debut);
                    c.lieu = MajusculePremiereLettre(html.Substring(index_debut, index_fin - index_debut));
                    
                    index_debut = IndexOfEx(html, "<span class=\"region\">", index_fin);
                    index_fin = html.IndexOf("</span>", index_debut);
                    morceau_lieu = html.Substring(index_debut, index_fin - index_debut);
                    if (morceau_lieu != "")
                    {
                        c.lieu = c.lieu + ", " + MajusculePremiereLettre(morceau_lieu);
                    }
                    index_debut = IndexOfEx(html, "<span class=\"country-name\">", index_fin);
                    index_fin = html.IndexOf("</span>", index_debut);
                    morceau_lieu = html.Substring(index_debut, index_fin - index_debut);
                    if (morceau_lieu != "")
                    {
                        c.lieu = c.lieu + ", " + morceau_lieu.ToUpper();
                    }

                    // Récupérer l'heure
                    index_debut = IndexOfEx(html, "<span class=\"dtstart\">", index_fin);
                    index_fin = html.IndexOf("<span ", index_debut);
                    c.heure = html.Substring(index_debut, index_fin - index_debut);

                    // Récupérer la date complete ! Merci Myspace, tellement plus simple qu'avant !
                    index_debut = IndexOfEx(html, "<span class=\"value-title\" title=\"", index_debut);
                    index_fin = html.IndexOf("\">", index_debut);
                    c.date = html.Substring(index_debut, index_fin - index_debut).Trim();

                    index_fin = IndexOfEx(html, "</li>", index_fin);
                    index_fin = html.IndexOf("</li>", index_fin);

                    compteur_ajouts++;
                    liste_concert.Add(c);
                }

                /* PROCEDURE AVANT MAJ DE MYSPACE...
                while (html.IndexOf("<div class='eventitem'>") != -1)
                {
                    html = html.Substring(IndexOfEx(html, "<div class='eventitem'>", index_fin));

                    c = new Concert();

                    // Récupérer le chemin d'accès de l'image du concert
                    index_event_atr = IndexOfEx(html, "<div class='event-img'>", 0);
                    index_debut = IndexOfEx(html, "<img src='", index_event_atr);
                    index_fin = html.IndexOf("'", index_debut);
                    c.chemin_img = html.Substring(index_debut, index_fin - index_debut);

                    // Récupérer le titre de l'évenement
                    string[] titre_lieu;
                    string[] separateur_lieu = { ", " };
                    index_event_atr = IndexOfEx(html, "<div class='event-titleinfo'>", 0);
                    index_debut = IndexOfEx(html, " at ", index_event_atr);
                    index_debut = IndexOfEx(html, "<span title=\"", index_debut);
                    index_fin = html.IndexOf("\"", index_debut);
                    titre_lieu = html.Substring(index_debut, index_fin - index_debut).Split(separateur_lieu, StringSplitOptions.RemoveEmptyEntries);

                    c.lieu = titre_lieu[titre_lieu.Length - 1 - 1];

                    c.titre = html.Substring(index_debut, index_fin - index_debut).Replace(", " + c.lieu + ",", "");
                    c.titre = c.titre.Trim();

                    // Récupérer la date et l'heure
                    string[] date_heure;
                    string[] separateur = { " @ " };
                    index_event_atr = IndexOfEx(html, "<div class='event-cal'>", 0);
                    index_debut = index_event_atr;
                    index_fin = html.IndexOf("</div>", index_debut);
                    date_heure = html.Substring(index_debut, index_fin - index_debut).Split(separateur, StringSplitOptions.RemoveEmptyEntries);
                    c.date = date_heure[0];
                    c.heure = date_heure[1];

                    compteur_ajouts++;
                    liste_concert.Add(c);
                }*/

            }
            return compteur_ajouts;
        }

    }
}
